package com.ljj.admin.web.controller.system;

import com.ljj.admin.common.utils.ServletUtils;
import com.ljj.admin.web.bean.common.AjaxResult;
import com.ljj.admin.web.bean.common.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginContorller {

    private Logger logger = LoggerFactory.getLogger(LoginContorller.class);


    @GetMapping("/")
    public String Begin()
    {

        return "redirect:/login";
    }


    @GetMapping("/login")
    public String Login(HttpServletRequest request, HttpServletResponse response) {

        //判断是否是ajax 登陆请求
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        return "login";
    }



    @ResponseBody
    @PostMapping("/loginIn")
    public AjaxResult LoginOn(String username, String password,boolean rememberMe) {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 记住我
        token.setRememberMe(rememberMe);

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return new AjaxResult(AjaxResult.Type.SUCCESS, "登录成功", null);
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return new AjaxResult(AjaxResult.Type.ERROR, msg, null);
        }

    }


    /**
     * 登出操作
     * @return
     */
    @GetMapping("/loginOut")
    public String loginOut()
    {

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }




}
